<template>
    <div class="enter-page">
        <div class="login-container">
          <div class="login">
            <div class="login-header">
              <h1>注册您的账号</h1>
            </div>
            <div class="login-form">
              <el-form
                  ref="ruleFormRef"
                  style="max-width: 680px"
                  :model="ruleForm"
                  status-icon
                  :rules="rules"
                  label-width="100px"
                  class="demo-ruleForm"
                  size="large"
              >
                <el-form-item label="账号" prop="account">
                  <el-input v-model="ruleForm.account" type="" autocomplete="off" 
                  placeholder="输入注册的账号" clearable/>
                </el-form-item>
                <el-form-item
                prop="email"
                label="邮箱"
                :rules="[
                    {
                    required: true,
                    message: '请输入邮箱地址',
                    trigger: 'blur',
                    },
                    {
                    type: 'email',
                    message: '请输入正确的邮箱地址',
                    trigger: ['blur', 'change'],
                    },
                    ]"
                >
                    <el-input v-model="ruleForm.email" 
                    placeholder="输入绑定的邮箱" clearable/>
                </el-form-item>
                <el-form-item label="密码" prop="pass">
                    <el-input v-model="ruleForm.pass" type="password" autocomplete="off" 
                    placeholder="输入您的密码" clearable/>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass">
                    <el-input v-model="ruleForm.checkPass" type="password"
                        autocomplete="off" placeholder="再次输入您的密码" clearable
                    />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitForm(ruleFormRef)">
                    确认注册
                  </el-button>
                  <el-button @click="resetForm(ruleFormRef)">清空</el-button>
                  <el-button @click="toLogin">回到登录页</el-button>
                </el-form-item>
              </el-form>
            </div>
            </div>
          </div>
    </div>
</template>
      
<script lang="ts" setup>
    /* eslint-disable no-unused-vars */
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import axios from 'axios'
import querystring from 'querystring'
import router from '../router'
import api from '../api'

const ruleFormRef = ref<FormInstance>()


const validateAccount = (rule: any, value: string, callback: any) => {
  const regex = /^[a-zA-Z][a-zA-Z0-9_]{5,17}$/;
  if (value === '') {
    callback(new Error('账号不能为空'))
  } else {
    if(!regex.test(value)){
        callback(new Error('账号满足：只能包含字母、数字、下划线，以字母开头，长度6-18位'))
    }else{
        callback()
    }
  }
}

const validatePass = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入您的密码'))
  } else if (value !== ruleForm.pass) {
    callback(new Error("两次输入的密码不一致"))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  account:"",
  pass: '',
  email:'',
  checkPass: '',
})
const rules = reactive<FormRules<typeof ruleForm>>({
  account: [{ validator: validateAccount, trigger: 'blur' }],
  pass: [{ validator: validatePass, trigger: 'blur' }],
  checkPass: [{ validator: validatePass, trigger: 'blur' }],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  try {
    await formEl.validate();
    console.log('submit!');
    console.log(ruleForm);
    submitBack();
   } catch (error) {
    console.log('error submit!', error);
  }
};

const submitBack=()=>{
    api.newRegist({
      username:ruleForm.account,
      userpwd:ruleForm.pass,
      email:ruleForm.email
    }).then(res => {
       console.log('完整响应数据:', res); // 输出完整的响应数据
       const customRes = res as unknown as { code: number; message: string };
       
       const code = customRes.code?? -1; 
       const message = customRes.message?? '未知错误'; 

       if(code===0){
            alert('注册成功，请登录');
            router.push({name: 'EnterPage'});
       }else{
            alert(message);
       }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const toLogin=()=>{
  router.push({name: 'EnterPage'});
  
}

</script>
    
<style scoped>
    .enter-page {
      font-family: Arial, sans-serif;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background-image: url('../assets/Login-background.jpg');
      background-size: cover;
      .login-container {
        background-color: #f7f8fa;
        border-radius: 8px;
        box-shadow: 0 10px 10px rgba(0, 0, 0, 0.1);
        width: 50vw; 
        min-height: 70vh; 
        align-items: center; 
        .login{
          margin-top:0px;
          .login-header {
            text-align: center;
            margin-top: 5rem;
            margin-bottom:2rem;
          }
        }
      }
    }
</style>
    